package com.example.ccj.b.c.dialogfragment.scancode;


import android.content.Context;
import android.hardware.Camera;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.MImageView;
import com.example.ccj.b.c.custom.MTextView;
import com.example.ccj.b.c.dialogfragment.BaseDialogFragment;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.VibrateUtils;
import com.example.ccj.u.media.IPictureSelectResultListener;
import com.example.ccj.u.media.MediaUtils;
import com.luck.picture.lib.entity.LocalMedia;
import java.util.ArrayList;

import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

/**
 * 扫码DialogFragment
 * 打开过慢
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/9 20:24
 */
public class ScanCodeDialogFragment extends BaseDialogFragment implements View.OnClickListener, QRCodeView.Delegate {

    private ZXingView zXingView;
    private MImageView flash;
    private MImageView qrCodeImg;
    private MImageView barCodeImg;
    private MTextView scanResult;
    private BaseRecycler<String> rec;

    private boolean isContinuity = false;//是否连扫
    private boolean flashIsOpen = false;
    private boolean barCodeIsOpen = false;
    private boolean qrCodeIsOpen = false;
    protected int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
    private final IScanCodeListener scanCodeListener;//获取到后回调

    public ScanCodeDialogFragment (Context context){
        super(context);
        scanCodeListener = null;
    }

    public ScanCodeDialogFragment (Context context,IScanCodeListener scanCodeListener){
        super(context);
        this.scanCodeListener = scanCodeListener;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_fragment_scan_code;
    }

    @Override
    protected void initViews(View v) {
        zXingView = v.findViewById(R.id.dialog_fragment_scan_code_zxing_scan_code_view);
        flash = v.findViewById(R.id.dialog_fragment_scan_code_flash);
        MImageView selectImg = v.findViewById(R.id.dialog_fragment_scan_code_select_img);
        LinearLayout barCode = v.findViewById(R.id.dialog_fragment_scan_code_bar_code);
        LinearLayout qrCode = v.findViewById(R.id.dialog_fragment_scan_code_qr_code);
        barCodeImg = v.findViewById(R.id.dialog_fragment_scan_code_bar_code_img);
        qrCodeImg = v.findViewById(R.id.dialog_fragment_scan_code_qr_code_img);
        MImageView switchCamera = v.findViewById(R.id.dialog_fragment_scan_code_switch_camera);
        scanResult = v.findViewById(R.id.dialog_fragment_scan_code_result_text);

        rec = v.findViewById(R.id.dialog_fragment_scan_code_rec);
        rec.setDefaultAdapter(new ArrayList<>(), R.layout.adapter_scan_code_text, (view, data) -> {
            TextView text = view.findViewById(R.id.adapter_scan_code_text);
            text.setText(data);
            return view;
        });

        flash.setOnClickListener(ScanCodeDialogFragment.this);     //闪光灯开关按钮事件
        selectImg.setOnClickListener(ScanCodeDialogFragment.this); //选择图片事件
        barCode.setOnClickListener(ScanCodeDialogFragment.this);   //切换条码事件
        qrCode.setOnClickListener(ScanCodeDialogFragment.this);    //切换二维码事件
        switchCamera.setOnClickListener(ScanCodeDialogFragment.this);    //切换二维码事件
    }

    @Override
    public void initData(){
        zXingView.setDelegate(ScanCodeDialogFragment.this);
        zXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        //打开闪光灯
        if (id == R.id.dialog_fragment_scan_code_flash) {
            if (flashIsOpen) {
                flash.setImageResource(R.mipmap.flash_grey);
                flashIsOpen = false;
                zXingView.closeFlashlight(); // 关闭闪光灯
            } else {
                flash.setImageResource(R.mipmap.flash);
                flashIsOpen = true;
                zXingView.openFlashlight(); // 打开闪光灯
            }
        //选择图片识别
        } else if (id == R.id.dialog_fragment_scan_code_select_img) {
            MediaUtils mediaUtils= new MediaUtils();
            mediaUtils.pickAPictureOrCamera(v.getContext(), new ArrayList<>(), new IPictureSelectResultListener() {
                @Override
                public void onResult(ArrayList<LocalMedia> result) {
                    if (!result.isEmpty()) {
                        zXingView.decodeQRCode(result.get(0).getRealPath());
                    }
                }
            });
        //修改是别类型为条码
        } else if (id == R.id.dialog_fragment_scan_code_bar_code) {
            if (barCodeIsOpen) {
                barCodeImg.setImageResource(R.mipmap.bar_code_grey);
                barCodeIsOpen = false;
                zXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
                zXingView.setType(BarcodeType.ALL, null); // 识别所有类型的码
                zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            } else {
                if (qrCodeIsOpen) {
                    qrCodeImg.setImageResource(R.mipmap.qr_code_grey);
                    qrCodeIsOpen = false;
                }
                barCodeImg.setImageResource(R.mipmap.bar_code);
                barCodeIsOpen = true;
                zXingView.changeToScanBarcodeStyle(); // 切换成扫描条码样式
                zXingView.setType(BarcodeType.ONE_DIMENSION, null); // 只识别一维条码
                zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            }
        //修改是别类型为二维码
        } else if (id == R.id.dialog_fragment_scan_code_qr_code) {
            if (qrCodeIsOpen) {
                qrCodeImg.setImageResource(R.mipmap.qr_code_grey);
                qrCodeIsOpen = false;
                zXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
                zXingView.setType(BarcodeType.ALL, null); // 识别所有类型的码
                zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            } else {
                if (barCodeIsOpen) {
                    barCodeImg.setImageResource(R.mipmap.bar_code_grey);
                    barCodeIsOpen = false;
                }
                qrCodeImg.setImageResource(R.mipmap.qr_code);
                qrCodeIsOpen = true;
                zXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
                zXingView.setType(BarcodeType.HIGH_FREQUENCY, null); // 只识别高频率格式，包括 QR_CODE、UPC_A、EAN_13、CODE_128
                zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            }
        //切换镜头
        } else if (id == R.id.dialog_fragment_scan_code_switch_camera) {
            zXingView.stopSpot();
            if (mCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
                zXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开后置摄像头开始预览
                mCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
            } else {
                zXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览
                mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
            }
            zXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        }
    }

    //扫码成功回调
    @Override
    public void onScanQRCodeSuccess(String result) {
        //震动
        VibrateUtils.vibrate(100);
        if (result != null) {
            if (scanCodeListener != null) scanCodeListener.onResult(result);
            scanResult.setText(result);
        }
        //是否连续识别
        if (isContinuity) {
            zXingView.startSpot(); // 继续识别
            rec.addDataOnTail(result);
        } else {
            dismiss();
        }
    }

    //摄像机环境亮度更改回调
    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = zXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                zXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                zXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    //相机打开错误回调
    @Override
    public void onScanQRCodeOpenCameraError() {
        LogUtils.e( "onScanQRCodeOpenCameraError() 扫码: " + "打开相机出错");
        ToastUtils.showShort("扫码失败，打开相机出错");
        dismiss();
    }


    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        if (zXingView != null) zXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (zXingView != null) zXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }


    public boolean isContinuity() {
        return isContinuity;
    }

    public void setContinuity(boolean continuity) {
        isContinuity = continuity;
    }


    public boolean isFlashIsOpen() {
        return flashIsOpen;
    }

    public boolean isBarCodeIsOpen() {
        return barCodeIsOpen;
    }

    public boolean isQrCodeIsOpen() {
        return qrCodeIsOpen;
    }

    public int getmCameraId() {
        return mCameraId;
    }
}
